// pages/login/login.js
const inputMixin = require('../../utils/mixins/input')
const navMixin = require('../../utils/mixins/nav')
const loading = require('../../utils/tools/loading')
const { userLogin } = require('../../utils/request/api')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '',
    password: '',
    errorMsg: '',
    dataMsg:'',  //登录后后台返回的data.msg
  },

  /**
   * @desc 登录
   */
  login(){
    console.log("点击了登录");

    let { dataMsg,mobile} = this.data;
    if (loading.isLoading) return
    let errorMsg = this.validate(this.getValidateOptions())
    if(errorMsg){
      return this.setErrorMsg(errorMsg)
    }
    this.clearErrorMsg()

    // 设置登录状态
    loading.show('登录中')

    // 登录请求
    wx.request({
      url: userLogin,
      method:'POST',
      header: {'content-type': 'application/x-www-form-urlencoded'},
      data: { phone: this.data.mobile, pwd: this.data.password},
      success:(res) => {
        console.log(res);
        let dataMsg = this.data.dataMsg;
        let {code,msg} = res.data;
        if(code == 200){
          this.setData({
            dataMsg:msg
          })
          //后台返回的msg存入storage，缓存清除后将再次登录
          try{
            wx.setStorageSync('dataMsg',this.data.dataMsg);
          }catch(e){
            return e.errorMsg()
          }

          loading.hide()
          wx.navigateTo({
            url: '/pages/index/index',
          })
        }else{
          loading.hide()
          wx.showModal({
            title: '提示',
            content: msg,
            showCancel:false,
          })
        } 
      },
      fail:(res) => {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: res,
          showCancel: false,
        })
      }
    })
  },

  /**
   * @desc 获取验证条件
   */
  getValidateOptions(){
    let { mobile, password } = this.data
    let data = [
      {
        value: mobile,
        strategies: [
          { strategy: 'isNotEmpty', errorMsg: '手机号码不能为空' },
          { strategy: 'isPhone', errorMsg: '手机号码格式不对' },
        ],
      },
      {
        value: password,
        strategies: [
          { strategy: 'isNotEmpty', errorMsg: '密码不能为空' },
        ],
      },
    ]

    return data
  },

  ...inputMixin,
  ...navMixin,
})